<?php

class Controller_Index extends Base_Controller
{

    public function home() {
        redirect('index', 'items');
    }
    
    public function items() {
        $data['tracks'] = db::fetchAll('SELECT * FROM `files`');
        $this->renderTpl('file-list.php', $data);
    }
    
    public function upload() {
        if(request::post('upload-submit-button') === null) {
            $this->renderTpl('upload-form.php');
        } else {
            $artist = request::post('artist');
            $title  = request::post('title');
            $tags   = request::post('tags');
            $info   = request::file('file');
            $code   = md5(mt_rand());
            move_uploaded_file($info['tmp_name'], ROOT . DS . 'uploads' . DS . $code . '.mp3');
            db::execute('INSERT INTO `files` (`artist`, `title`, `tags`, `filecode`) VALUES (?, ?, ?, ?)',
                array($artist, $title, $tags, $code)
            );
            redirect('index', 'items');
        }  
    }
    
    public function play() {
        $id = request::get('id', -1);
        $data = $this->model->file->getById($id);;
        $path = ROOT . DS . 'uploads' . DS . $data['filecode'] . '.mp3';
        $fileName = sprintf('%s - %s.mp3', $data['artist'], $data['title']);
        header('Content-type: audio/mpeg');
        header('Content-Length: ' . sprintf("%u", filesize($path)));
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        header('Expires: 10000');
        header('Pragma: public');
        clearstatcache();
        readfile($path);
    }
   

}